package org.raymond.iworks.study.netty.official.fundamental.time;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * @author raymond
 * @version V1.0
 * @Description: TODO
 */
public class TimeClient {
    public static void main(String[] args) throws Exception {
        String host = "127.0.0.1";
        int port = 8080;
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            Bootstrap b = new Bootstrap(); // 不同于ServerBootstrap适用于服务端, Bootstrap适用于客户端或无连接channel
            b.group(workerGroup); // 如果你只用了一个EventLoopGroup,那么它将被用在boos和worker上.只是客户端用不上boss事件池。
            b.channel(NioSocketChannel.class); // NioSocketChannel用于创建客户端channel
            b.option(ChannelOption.SO_KEEPALIVE, true); // 注意我们没有使用childOption(),因为客户端SocketChannel没有父节点
            b.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new TimeReplayingDecoder2()).addLast(new TimeClientHandler2());
                }
            });

            // Start the client.
            ChannelFuture f = b.connect(host, port).sync(); // 客户端应该调用connect()方法而不是bind()方法

            // Wait until the connection is closed.
            f.channel().closeFuture().sync();
        } finally {
            workerGroup.shutdownGracefully();
        }
    }
}
